<?php

namespace app\admin\controller\scanwork;

/**
 * 工厂功能Trait
 * 为现有控制器提供工厂相关的通用方法
 */
trait FactoryTrait
{
    /**
     * 获取当前用户的工厂ID列表
     */
    protected function getUserFactoryIds()
    {
        $userId = $this->auth->id;
        $factoryIds = \app\admin\model\scanwork\UserFactory::where('user_id', $userId)
            ->where('status', 1)
            ->column('factory_id');
        
        // 如果没有关联工厂，返回空数组（表示无权限）
        return $factoryIds ?: [];
    }

    /**
     * 获取当前用户可访问的工厂列表
     */
    protected function getUserFactories()
    {
        $factoryIds = $this->getUserFactoryIds();
        if (empty($factoryIds)) {
            return [];
        }
        
        return \app\admin\model\scanwork\Factory::where('id', 'in', $factoryIds)
            ->where('status', 1)
            ->order('sort asc, id asc')
            ->select();
    }

    /**
     * 检查用户是否有访问指定工厂的权限
     */
    protected function checkFactoryPermission($factoryId)
    {
        $userFactoryIds = $this->getUserFactoryIds();
        return in_array($factoryId, $userFactoryIds);
    }

    /**
     * 获取当前选中的工厂ID
     */
    protected function getCurrentFactoryId()
    {
        // 优先从请求参数获取
        $factoryId = $this->request->param('factory_id');
        if ($factoryId && $this->checkFactoryPermission($factoryId)) {
            return $factoryId;
        }

        // 从session获取
        $factoryId = session('current_factory_id');
        if ($factoryId && $this->checkFactoryPermission($factoryId)) {
            return $factoryId;
        }

        // 获取用户第一个有权限的工厂
        $userFactoryIds = $this->getUserFactoryIds();
        if (!empty($userFactoryIds)) {
            $factoryId = $userFactoryIds[0];
            session('current_factory_id', $factoryId);
            return $factoryId;
        }

        return null;
    }

    /**
     * 设置当前工厂ID
     */
    protected function setCurrentFactoryId($factoryId)
    {
        if ($this->checkFactoryPermission($factoryId)) {
            session('current_factory_id', $factoryId);
            return true;
        }
        return false;
    }

    /**
     * 为查询条件添加工厂过滤
     */
    protected function addFactoryFilter($where = [])
    {
        $factoryId = $this->getCurrentFactoryId();
        if ($factoryId) {
            $where['factory_id'] = $factoryId;
        } else {
            // 如果没有工厂权限，返回一个不可能的条件
            $where['factory_id'] = -1;
        }
        return $where;
    }

    /**
     * 为模型查询添加工厂过滤
     */
    protected function addFactoryScope($query)
    {
        $factoryId = $this->getCurrentFactoryId();
        if ($factoryId) {
            $query->where('factory_id', $factoryId);
        } else {
            // 如果没有工厂权限，返回空结果
            $query->where('factory_id', -1);
        }
        return $query;
    }

    /**
     * 为新记录设置工厂ID
     */
    protected function setFactoryId($data)
    {
        $factoryId = $this->getCurrentFactoryId();
        if ($factoryId) {
            $data['factory_id'] = $factoryId;
        }
        return $data;
    }

    /**
     * 获取工厂选择器数据
     */
    protected function getFactorySelectData()
    {
        $factories = $this->getUserFactories();
        $data = [];
        foreach ($factories as $factory) {
            $data[$factory->id] = $factory->name;
        }
        return $data;
    }

    /**
     * 在视图中分配工厂相关数据
     */
    protected function assignFactoryData()
    {
        $this->view->assign('userFactories', $this->getUserFactories());
        $this->view->assign('currentFactoryId', $this->getCurrentFactoryId());
        $this->view->assign('factorySelectData', $this->getFactorySelectData());
    }
}
